<?php

namespace Home\Controller;

/**
 * Description of AccountController.class控制器实例
 *
 * @author songanwei
 * @date 2016-1-4
 */
class AccountController extends ParentController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * @description 更新账户密码
     * @modify songanwei 2016-01-04
     */
    public function updatePassword() {
        $oldPassword = I('post.oldPassword');
        $newPassword = I('post.newPassword');
        $vcode = I('post.vcode');
        $userId = getUserId();
        //验证参数
        $this->ajaxValidateReturn($this->validateUtil, $oldPassword, "password");
        $this->ajaxValidateReturn($this->validateUtil, $newPassword, "password");
        $this->ajaxValidateReturn($this->validateUtil, $vcode, "vcode");
        //检查验证码
        if (!checkVcode($vcode)) {
            returnJson(403, 122);
        }
        //查询账户并验证原密码
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfo($userId);
        if ($adminLogin['password'] != hash('sha256', $oldPassword)) {
            returnJson(403, 102);
        }
        //更新用户密码
        $result = $adminLoginModel->setPassword($userId, hash('sha256', $newPassword));
        if ($result == false) {
            returnJson(500, 509);
        }
        sendTcpClientMsg($userId, 'password_modified', null);
        returnJson(200, 200);
    }

    /**
     * @description 更新账户名称
     * @modify songanwei 2016-01-04
     */
    public function updateUserInfo() {
        $name = I('post.name');
        $head = I('post.head');
        $userId = getUserId();
        //验证参数
        $this->ajaxValidateReturn($this->validateUtil, $name, "nameLength20");
        //查询账号
        $adminLoginLogic = A('Common/AdminLogin', 'Logic');

        $adminLoginLogic->saveInfo($userId, $name, $head);
        //更新头像session
        session(C('USER_HEAD'), $head);
        session(C('USER_NAME'), $name);
        returnJson(200, 200);
    }

    /**
     * @description 添加客栈子账号
     * @modify songanwei 2016-01-04
     * @modify trainyao 2016-06-06 修正不是该客栈的超级管理员不能操作子管理员
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function addSub() {
        $param = I('post.');

        //检查参数
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'name' => 'notnull,notempty,username',
            //'mobile' => 'notnull,notempty,mobile',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }

        $name = $param['name'];
        $mobile = $param['mobile'];
        $hotelId = $param['hotel'];
        $userId = getUserId();
        $areaCode = I('post.areaCode', '86', 'string');

        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        /*
        //检查操作权限
        $adminHotelModel = D('AdminHotel');
        $result = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($result)) {
            returnJson(403, 202);
            return;
        }
        $result = getArrayValueAsIndex($result, 'hotelentity_id');
        if (!isset($result[$hotelId])) {
            returnJson(403, 202);
            return;
        }
        */

        $AccountLogic = A('Common/Account', 'Logic');
        $AccountLogic->addSub($userId, $mobile, $name, $areaCode);
        returnJson(200, 200);
    }

    /**
     * @description 删除客栈子账号
     * @modify songanwei 2015-01-04
     */
    public function deleteSub() {
        $param = I('post.');

        //检查参数
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'account' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }

        $hotelId = $param['hotel'];
        $accountId = $param['account'];
        $userId = getUserId();

        /*
        // 验证操作权限
        $adminHotelModel = D('AdminHotel');
        $result = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($result)) {
            returnJson(403, 202);
        }
        $result = getArrayValueAsIndex($result, 'hotelentity_id');
        if (!isset($result[$hotelId])) {
            returnJson(403, 202);
            return;
        }
        */

        //删除账号
        $accountLogic = A('Common/Account', 'Logic');
        $accountLogic->deleteSub($userId, $accountId);

        returnJson(200, 200);
    }

    /**
     * @description 更新权限||authority数据格式 array('0'=>array('hotelId'=>4,'authorityStr'=> '1,2,3,4,5,6')
     * @modify songanwei 2016-01-04
     */
    public function setAuthority() {
        $accountId = I('post.account');
        $authorities = I('post.authority');
        $userId = getUserId();
        $this->ajaxValidateReturn($this->validateUtil, $accountId, "id");

        //检查操作权限
        $adminHotelModel = D('AdminHotel');
        $result = $adminHotels = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($result)) {
            returnJson(403, 202);
        }
        //检查数据
        $hotelIdArray = array_column($adminHotels, "hotelentity_id");
        foreach ($authorities as $authority) {
            if (!in_array($authority['hotelId'], $hotelIdArray)) {
                returnJson(403, 202);
            }
        }

        $accountLogic = A('Common/Account', 'Logic');
        $accountLogic->setAuthority($userId, $accountId, $authorities);
        returnJson(200, 200);
    }

    /**
     * @description 获取当前客栈下的所有用户权限数据
     * @modify songanwei 2016-01-08
     */
    public function getAuthority() {
        $accountId = I('post.account');
        $userId = getUserId();
        $this->ajaxValidateReturn($this->validateUtil, $accountId, "id");
        $accountLogic = A('Common/Account', 'Logic');
        $authority = $accountLogic->getAuthority($userId, $accountId);
        returnJson(200, 200, $authority);
    }

    /**
     * @description  账户安全 发送验证码到已绑定手机
     * @modify songanwei 2016-01-08
     */
    public function sendMobile() {
        // 检测60秒防刷
        $mobileSendTime = session(C('SERCURE_MOBILE_VCODE_TIME')) ? session(C('SERCURE_MOBILE_VCODE_TIME')) : 0;
        $result = time() - $mobileSendTime - 60;
        $userId = getUserId();

        //可再次发送短信验证码
        if ($result > 0) {
            $adminLoginModel = D('AdminLogin');
            $adminLogin = $adminLoginModel->getInfo($userId);
            $mobile = $adminLogin['mobile'];
            $areacode = $adminLogin['areacode'];
            $mobileVcode = getRandomNumber();

            //发送短信
            if ($areacode == '86') {
                $smsUtil = new \Org\Util\Sms();
                $result = $smsUtil->sendVocode($mobile, $mobileVcode);
            } else {
                $smsUtil = new \Org\Util\yunPian();
                $result = $smsUtil->sendVcode($areacode, $mobile, $mobileVcode);
            }
            
            if (!$result) {
                returnJson(403, 151, 'error');
            }
            //session保存验证码
            session(C('SERCURE_MOBILE_VCODE'), $mobileVcode);
            //session保存验证码发送时间
            session(C('SERCURE_MOBILE_VCODE_TIME'), time());
            //session保存验证码有效结束时间
            session(C('SERCURE_MOBILE_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_VCODE_END_TIME_EFFECTIVE'));
            returnJson(200, 200, 'success');
        } else {
            returnJson(403, 107, 'error');
        }
    }

    /**
     * @description 验证手机短信验证码
     * @modify songanwei 2016-01-08
     */
    public function verifyWithMobile() {
        $param = I('post.');
        $mobileCode = $param['vcode'];
        // 校验验证码
        $this->ajaxValidateReturn($this->validateUtil, $mobileCode, 'vcode6');

        //获取验证码结束时间
        $mobileVcodeEndTime = session(C('SERCURE_MOBILE_VCODE_END_TIME'));
        //获取验证码
        $mobileVcode = session(C('SERCURE_MOBILE_VCODE'));
        // 与session内的效验码以及过期时间进行比对
        if (($mobileVcode != $mobileCode) || ($mobileVcodeEndTime <= time())) {
            returnJson(403, 120);
        }
        session(C('SERCURE_MOBILE_VCODE'), null);
        session(C('SERCURE_MOBILE_VCODE_TIME'), null);
        session(C('SERCURE_MOBILE_VCODE_END_TIME'), null);
        returnJson(200, 200);
    }

    /**
     * @description 发送新手机短信验证码
     * @modify songanwei 2016-01-08
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendMobileNew() {
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $adminLoginModel = D('AdminLogin');
        //检查手机号是否与之前手机号一样
        $userId = getUserId();
        $adminLogin = $adminLoginModel->getInfo($userId);
        if ($adminLogin['mobile'] == $mobile) {
            returnJson(403, 106);
        }
        //检查手机号是否已被注册
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if ($adminLogin) {
            returnJson(403, 105);
        }

        // 检测60秒防刷
        $mobileSendTime = session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) ? session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) : 0;
        $result = time() - $mobileSendTime - 60;


        //可再次发送短信验证码
        if ($result > 0) {
            $mobileVcode = getRandomNumber();
            //发送短信
            if ($areaCode == '86') {
                $smsUtil = new \Org\Util\Sms();
                $result = $smsUtil->sendVocode($mobile, $mobileVcode);
            } else {
                $yunPian = new \Org\Util\yunPian();
                $result = $yunPian->sendVcode($areaCode, $mobile, $mobileVcode);
            }

            if (!$result) {
                returnJson(403, 151, 'error');
            }
            
            //保存新手机号
            session(C('SERCURE_MOBILE_NEW'), $mobile);
            //session保存验证码
            session(C('SERCURE_MOBILE_NEW_VCODE'), $mobileVcode);
            //session保存验证码发送时间
            session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), time());
            //session保存验证码有效结束时间
            session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_NEW_VCODE_END_TIME_EFFECTIVE'));
            returnJson(200, 200, 'success');
        } else {
            returnJson(403, 107, 'error');
        }
    }

    /**
     * @description 验证并更换新手机号
     * @modify songanwei 2016-01-08
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function verifyWithMobileNew() {
        $vcode = I('post.vcode');
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        $this->ajaxValidateReturn($this->validateUtil, $vcode, 'vcode6');
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $userId = getUserId();
        //检查数据
        $mobileNew = session(C('SERCURE_MOBILE_NEW'));
        if (!$mobileNew) {
            returnJson(500, 501);
        }
        //获取验证码结束时间
        $mobileVcodeEndTime = session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'));
        //获取验证码
        $mobileVcode = session(C('SERCURE_MOBILE_NEW_VCODE'));
        //验证新的短信手机
        if (($mobileNew != $mobile) || ($vcode != $mobileVcode) || ($mobileVcodeEndTime <= time())) {
            returnJson(403, 120);
        }
        $adminLoginModel = D('AdminLogin');
        //更换手机号
        $result = $adminLoginModel->setMobile($userId, $mobileNew, $areaCode);
        if ($result == false) {
            returnJson(500, 509);
        }
        session(C('SERCURE_MOBILE_NEW_VCODE'), null);
        session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), null);
        session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), null);
        returnJson(200, 200);
    }

    /**
     * @description 检查用户是否已存在
     * @modify songanwei 2016-02-02
     */
    public function checkUserExist() {
        $params = I('post.');
        $adminLoginModel = D('AdminLogin');
        $mobile = $params['mobile'];
        $areaCode = isset($params['areaCode']) ? $params['areaCode'] : '86';
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$adminLogin) {
            returnJson(403, 100);
        }
        returnJson(200, 200, array('name' => $adminLogin['name']));
    }

    /**
     * 获取公共推广链接信息
     * @modify trainyao 2016-06-06    创建
     */
    public function publicLinkInfo() {
        $userId = getUserId();

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        if (empty($adminAuthorityLogic->checkIsAdmin($userId))) {
            returnJson(403, 202);
            return;
        }

        $adminDetailModel = D('AdminDetail');
        $publicLinkInfo = $adminDetailModel->getInfoByUser($userId);

        $hashIdsUtil = new \Org\Util\Hashids(C('HASHIDS_SALT'), 16);
        returnJson(200, 200, array(
            'link' => 'http://' . MEIZHU_BOOK_HOST . '/Home/BookPage/popularize?no=' . $hashIdsUtil->encode($userId),
            'name' => isset($publicLinkInfo['name']) ? $publicLinkInfo['name'] : '',
            'imageUrl' => isset($publicLinkInfo['imageurl']) ? MEIZHU_URL . $publicLinkInfo['imageurl'] : '',
        ));
    }

    /**
     * 保存公共推广链接信息
     * @modify trainyao 2016-06-06    创建
     */
    public function savePublicLinkInfo() {
        $param = I('post.');

        $validateRule = array(
            'name' => 'notempty,nameLength20',
            'imageUrl' => 'notempty,nameLength255',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }

        // 校验是否有超级管理员权限
        $userId = getUserId();
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        if (empty($adminAuthorityLogic->checkIsAdmin($userId))) {
            returnJson(403, 202);
            return;
        }

        $name = isset($param['name']) ? $param['name'] : null;
        $imageUrl = isset($param['imageUrl']) ? $param['imageUrl'] : null;
        $returnData = array();
        if (empty($name) && empty($imageUrl)) {
            returnJson(200, 200, $returnData);
            return;
        }
        if (!empty($imageUrl)) {
            $imageUrl = str_replace(MEIZHU_URL, '', $imageUrl);
        }

        $adminDetailModel = D('AdminDetail');
        $publicLinkInfo = $adminDetailModel->getInfoByUser($userId);
        if (empty($publicLinkInfo)) {
            $saveResult = $adminDetailModel->addInfo($userId, $name, $imageUrl);
        } else {
            $saveResult = $adminDetailModel->saveInfo($userId, $name, $imageUrl);
        }
        if (empty($saveResult)) {
            returnJson(500, 506);
            return;
        }

        if (!empty($imageUrl)) {
            $returnData['imageUrl'] = MEIZHU_URL . $imageUrl;
        }
        returnJson(200, 200, $returnData);
    }

    /**
     * 获取子管理员房间权限
     * @modify trainyao 2016-06-28    创建
     */
    public function roomAuthority() {
        $param = I('post.');
        $validateRule = array(
            'account' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }

        $adminId = getUserId();
        $accountId = $param['account'];
        $accountLogic = A('Common/Account', 'Logic');
        try {
            $hotelRoomAuthority = $accountLogic->getRoomAuthority($adminId, $accountId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
		
        // 格式化数据
        foreach ($hotelRoomAuthority as &$hotelRoomAuthorityItem) {
            foreach ($hotelRoomAuthorityItem['roomType'] as &$roomTypeItem) {
                foreach ($roomTypeItem['room'] as &$roomItem) {
                    $roomItem = array(
                        'room' => $roomItem['id'],
                        'name' => $roomItem['name'],
                        'enable' => $roomItem['roomAuthority'],
                    );
                }
                unset($roomItem);

                $roomTypeItem = array(
                    'name' => $roomTypeItem['name'],
                    'room' => array_values($roomTypeItem['room']),
                );
            }
            unset($roomTypeItem);

            $hotelRoomAuthorityItem = array(
                'hotel' => $hotelRoomAuthorityItem['hotelentity_id'],
                'name' => $hotelRoomAuthorityItem['name'],
                'roomType' => array_values($hotelRoomAuthorityItem['roomType']),
            );
        }
        unset($hotelRoomAuthorityItem);

        returnJson(200, 200, $hotelRoomAuthority);
    }

    /**
     * 保存子管理员房间权限
     * @modify trainyao 2016-06-28 创建
     */
    public function setRoomAuthority() {
        $param = I('post.');
        $validateRule = array(
            'account' => 'notnull,notempty,id',
            'authority' => 'notnull',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }

        // 校验权限ID格式
        $authority = $param['authority'];
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
        );
        $hasRoomAuthorityHotelId = array();
        foreach ($authority as &$hotelRoomAuthorityItem) {
            if (empty($hotelRoomAuthorityItem['room'])) {
                unset($validateRule['room']);
            } else {
                array_push($hasRoomAuthorityHotelId, $hotelRoomAuthorityItem['hotel']);
                $validateRule['room'] = 'notnull,notempty,concatId';
            }
            $validatePass = $this->ajaxValidateReturn($this->validateUtil, $hotelRoomAuthorityItem, $validateRule);
            if (empty($validatePass)) {
                return;
            }

            $hotelRoomAuthorityItem['room'] = empty($hotelRoomAuthorityItem['room']) ? array() : explode(',', $hotelRoomAuthorityItem['room']);
        }
        unset($hotelRoomAuthorityItem);

        $adminId = getUserId();
        $accountId = $param['account'];
        $hotelRoomAuthorityModel = D('HotelRoomAuthority');
        $hotelRoomAuthorityModel->startTrans();
        $commit = true;

        // 检查需要保存房间权限的客栈,被操作者是否都作为子管理员
        if (!empty($hasRoomAuthorityHotelId)) {
            $adminHotelModel = D('AdminHotel');
            $managerHotelId = $adminHotelModel->getInfosByAdmin($accountId, HOTEL_ROLE_MANAGER);
            $managerHotelId = array_column($managerHotelId, 'hotelentity_id');
            if (!empty(array_diff($hasRoomAuthorityHotelId, $managerHotelId))) {
                returnJson(403, 413);
                return;
            }
        }

        // 保存房间权限
        $accountLogic = A('Common/Account', 'Logic');
        try {
            $accountLogic->saveRoomAuthority($adminId, $accountId, $authority, true);
        } catch (\Exception $e) {
            $commit = false;
            $hotelRoomAuthorityModel->rollback();
            returnJson($e->getMessage());
            return;
        }

        if (!$commit) {
            $hotelRoomAuthorityModel->rollback();
            returnJson(500, 506);
            return;
        }

        $hotelRoomAuthorityModel->commit();
        returnJson(200, 200);
    }

    /**
     * 获取子管理员信息ajax接口
     * @modify trainyao 2016-07-26    创建
     */
    public function info() {
        // 获取所有组信息
        $userId = getUserId();
        $groupLogic = A('Common/Group', 'Logic');
        $groupInfo = $groupLogic->getInfoByUser($userId);
        foreach ($groupInfo as &$groupInfoItem) {
            $groupInfoItem = array(
                'id' => $groupInfoItem['id'],
                'name' => $groupInfoItem['name'],
            );
        }
        unset($groupInfoItem);

        // 获取超级管理员管理的客栈
        $accountLogic = A('Common/Account', 'Logic');
        $accounts = $accountLogic->getSub($userId);

        returnJson(200, 200, array(
            'group' => $groupInfo,
            'account' => $accounts,
        ));
    }
	/**
     * 申请正式版
     * @modify zhangzhen 2016-12-29    创建
     */
	/*public function applyNormal() {
		$userId = getUserId();
		$adminLoginModel = D('AdminLogin');
		$adminLoginModel->setStatus($userId, 2);
		returnJson(200, 200);
	}*/
}
